package cn.szzsi.platform.controller.admin;

import cn.szzsi.AConfig;
import cn.szzsi.business.service.CompanyInfoService;
import cn.szzsi.common.util.CommonUtil;
import cn.szzsi.common.util.HttpExtKit;
import cn.szzsi.model.CompanyInfo;
import cn.szzsi.model.Member;
import cn.szzsi.model.mall.Business;
import cn.szzsi.model.mall.ProductCategory;
import cn.szzsi.model.mall.SiteConfig;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 超级管理员对商户的管理
 * Created by admin on 2017/7/7.
 */
public class BusinessController extends Controller{
    public void list(){
        render(CommonUtil.TEMPLATE_PATH + "/platform/business/member_list_business.html");
    }
    public void ajaxlist() {
        List<Member> lpa = Member.dao.find("select m.id,m.username,m.loginDate,m.createDate,c.userId,c.phone,c.email,c.isDisable,c.personInCharge,c.sortNo from sys_member m LEFT JOIN sys_company_info c on m.id=c.shopId where m.b_shoprank='super' and c.status='2' order by m.createDate desc");
        renderJson(lpa);
    }

    public void add(){
        setAttr("productFirstCategoryList", ProductCategory.dao.getFirstMenu("-1"));
        render(CommonUtil.TEMPLATE_PATH + "/platform/business/member_input_business.html");
    }

    /**
     * L超级管理员保存商户
     */
    @Before(Tx.class)
    public void save() {
        String regPhone = "^0?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[57])[0-9]{8}$" ; //手机正则表达式
        String username = getPara("username", "");//用户名
        String password = getPara("password");//密码
        String userimgurl=getPara("userimgurl");//用户头像
        String phone = getPara("phone");//联系电话
        if(StrKit.isBlank(username)){
            username=phone;
        }

        //企业信息
        String brandLogo=getPara("brandLogo");//品牌方LOGO
        String personInCharge=getPara("personInCharge");//运营者姓名
        String brandName=getPara("brandName");//品牌商名称
        String company_name=getPara("company_name");//企业名称
        String business_licence_code=getPara("business_licence_code");//营业执照注册号
        String business_licence_img=getPara("business_licence_img");//营业执照扫描件
        String categories=getPara("category_one")+","+getPara("category_two");//类目
        String email=getPara("email");//邮箱
        String weChat=getPara("weChat");//微信号
        String qq=getPara("qq");//QQ号码
        String productCategoryId=getPara("productCategoryId");//商品分类
        Integer sortNo=getParaToInt("sortNo",0);
        //Member isExsitMember=Member.dao.getCustomerByUsernameAndShopId(username,"0");
        /*if(!phone.matches(regPhone)){
            renderJson(Ret.fail("info","请输入正确的手机号"));
            return;
        }*/
        if(CompanyInfoService.cis.isExistByPhone(phone,"")){
            renderJson(Ret.fail("info","添加失败,手机号已被注册!"));
            return;
        }
        if(Member.dao.getCustomerByUsernameAndShopId(username,"0")!=null){
            renderJson(Ret.fail("info","添加存失败,商户已存在"));
            return;
        }
        if(StrKit.isBlank(password)){
            password=phone;
        }

        //保存商户基本信息
        //1.保存之前,先判断用户身份:类型:0-代理商和商户,1-商户,2-代理商
        Member phoneMember=Member.dao.getByPhone(phone);
        if(phoneMember==null){//既不会代理商,也不是商户
            phoneMember=Member.saveBusiness(phone,username,DigestUtils.md5Hex(password),userimgurl);
        }else{
            if(2==phoneMember.getType()){//代理商
                phoneMember.setType(0);
                phoneMember.setUsername(username);
                phoneMember.set("password", DigestUtils.md5Hex(password));
                phoneMember.set("userimgurl", userimgurl);
                phoneMember.set("shopId", "0");
                phoneMember.set("createDate", new Date());
                phoneMember.set("roleId", "super");
                phoneMember.set("b_shoprank", "super");
                phoneMember.set("isAccountEnabled", 1);
                phoneMember.set("isAccountLocked", 0);
                phoneMember.set("loginFailureCount", 0);
                phoneMember.set("phone", phone);
                phoneMember.set("registerIp", "");
                phoneMember.setType(0);//将代理商身份更改为双重身份
                phoneMember.update();
            }
        }
        /**
         * 企业相关信息保存
         */
        CompanyInfoService.cis.sysSaveInfo(company_name,business_licence_code,business_licence_img,phone,email,brandName,personInCharge,categories,"2",phoneMember.getId(),brandLogo,weChat,qq,productCategoryId,sortNo);//超级管理员添加的默认是审核通过的

        //保存商户排序
        Business business=new Business();
        business.setShopId(phoneMember.getId());
        business.setSortNo(sortNo);
        business.setId(StrKit.getRandomUUID());
        business.setCreateDate(new Date());
        business.setIsDisable("0");
        business.save();
        //保存商户排序

        //保存siteConfig
        SiteConfig sc=new SiteConfig();
        sc.setUid(phoneMember.getId());
        sc.setPhone(phone);
        sc.setShopAlias(phone);
        sc.setCreateDate(new Date());
        sc.save();
        //保存siteConfig
        renderJson(Ret.ok("info","保存成功!").set("url","list"));
    }


    public void edit() {
        String id = getPara("id", "");//商户id
        if (StrKit.notBlank(id)) {
            setAttr("member", Member.dao.findById(id));
        }
        setAttr("productFirstCategoryList", ProductCategory.dao.getFirstMenu("-1"));
        CompanyInfo companyInfo=CompanyInfo.dao.getByShopId(id);
        setAttr("companyInfo",companyInfo);
        render(CommonUtil.TEMPLATE_PATH + "/platform/business/member_input_business.html");
    }
    /**
     * L超级管理员更新商户
     */

    public void update() {
        Member member = getModel(Member.class);
        String password = getPara("password");//密码
        String userimgurl=getPara("userimgurl");//用户头像
        String regPhone = "^0?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[57])[0-9]{8}$" ; //手机正则表达式
        Integer sortNo=getParaToInt("sortNo",0);

        //企业信息
        String brandLogo=getPara("brandLogo");//品牌方LOGO
        String personInCharge=getPara("personInCharge");//运营者姓名
        String brandName=getPara("brandName");//品牌商名称
        String company_name=getPara("company_name");//企业名称
        String business_licence_code=getPara("business_licence_code");//营业执照注册号
        String business_licence_img=getPara("business_licence_img");//营业执照扫描件
        String categories=getPara("category_one")+","+getPara("category_two");//类目
        String phone = getPara("phone");//联系电话
        String email=getPara("email");//邮箱
        String weChat=getPara("weChat");//微信号
        String qq=getPara("qq");//QQ号码
        String productCategoryId=getPara("productCategoryId");//商品分类
        /*if(StrKit.isBlank(userimgurl)){
            renderJson(Ret.fail("info","保存失败,商户LOGO不允许为空"));
            return;
        }*/
        /*if(!phone.matches(regPhone)){
            renderJson(Ret.fail("info","请输入正确的手机号"));
            return;
        }*/
        if(CompanyInfoService.cis.isExistByPhone(phone,member.getId())){
            renderJson(Ret.fail("info","更新失败,手机号已被注册!"));
            return;
        }
        /*if(CompanyInfoService.cis.isExistByEmail(email,member.getId())){
            renderJson(Ret.fail("info","添加失败,邮箱已被注册!"));
            return;
        }*/

        //修改商户登陆
        member.set("userimgurl", userimgurl);
        if(StrKit.notBlank(password)){
            member.set("password", DigestUtils.md5Hex(password));
        }
        member.set("shopId", "0");
        member.set("modifyDate", new Date());
        member.set("phone", phone);
        member.update();

        //修改商户登记信息
        CompanyInfoService.cis.sysUpdateInfo(company_name,business_licence_code,business_licence_img,phone,email,brandName,personInCharge,categories,member.getId(),brandLogo,weChat,qq,productCategoryId,sortNo);

        //保存商户排序
        Business business=Business.dao.getByShopId(member.getId());
        if(business!=null){
            business.setSortNo(sortNo);
            business.update();
        }else{
            Business addBusiness=new Business();
            addBusiness.setShopId(member.getId());
            addBusiness.setSortNo(sortNo);
            addBusiness.setId(StrKit.getRandomUUID());
            addBusiness.setCreateDate(new Date());
            addBusiness.use(CommonUtil.ZSHOP_MALL).save();
        }
        //保存商户排序
        renderJson(Ret.ok("info","修改成功!").set("url","list"));
    }

    /**
     * 是否禁用商户
     */
    public void updateDisable(){
        String shopId=getPara("id");
        String isDisable=getPara("isDisable");
        CompanyInfo companyInfo=CompanyInfo.dao.getByShopId(shopId);
        Business business=Business.dao.getByShopId(shopId);
        if(companyInfo==null || business==null){
            renderJson(Ret.fail("info","操作失败!"));
            return;
        }
        companyInfo.setIsDisable(isDisable);
        business.setIsDisable(isDisable);
        companyInfo.update();
        business.update();

        Map map=new HashMap();
        map.put("shopId",shopId);
        map.put("isDisable",isDisable);
        HttpKit.get(AConfig.p.get("mall_web.url")+"/api/updateBusinessDisableStatus",map);
        renderJson(Ret.ok("info","操作成功!"));

    }

    /**
     * L管理员删除商户
     */
    @Before(Tx.class)
    public void delete() {
        String shopId=getPara("id");//商户id
        SiteConfig siteConfig=SiteConfig.dao.findByShopId(shopId);//店铺配置
        CompanyInfo companyInfo=CompanyInfo.dao.getByShopId(shopId);//商户配置
        Business business=Business.dao.getByShopId(shopId);
        siteConfig.delete();
        companyInfo.delete();
        business.delete();
        Member.dao.deleteById(shopId);

        Map map=new HashMap();
        map.put("shopId",shopId);
        HttpKit.get(AConfig.p.get("mall_web.url")+"/api/deleteRelationBusiness",map);
        renderJson(Ret.ok("info","删除成功!"));
    }

}
